const QQMapWX = require('../libs/qqmap-wx-jssdk.min.js');
const moment = require('../libs/moment.js');
import config from './config'
// 是否播放中
let innerAudioContext = null; 
// 中文
moment.locale('zh-cn');

Number.prototype.formatMoney = function (places, symbol, thousand, decimal) {
  places = !isNaN(places = Math.abs(places)) ? places : 2;
  symbol = symbol !== undefined ? symbol : "";
  thousand = thousand || ",";
  decimal = decimal || ".";
  let number = this,
    negative = number < 0 ? "-" : "",
    i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
    j = (j = i.length) > 3 ? j % 3 : 0;
  return symbol + negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
};


function formatTime(time) {
  if (typeof time !== 'number' || time < 0) {
    return time
  }

  let hour = parseInt(time / 3600)
  time = time % 3600
  let minute = parseInt(time / 60)
  time = time % 60
  let second = time

  return ([hour, minute, second]).map(function (n) {
    n = n.toString()
    return n[1] ? n : '0' + n
  }).join(':')
}

function getDate() {
  let time = new Date()
  let year = time.getFullYear()
  let month = time.getMonth() + 1
  month = month < 10 ? '0' + month : month
  let day = time.getDate()
  day = day < 10 ? '0' + day : day
  return [year, month, day].join('-')
}

function getYearAndMonth() {
  // new Date() - 24 * 60 * 60 * 1000
  let time = new Date()
  let year = time.getFullYear()
  let month = time.getMonth() + 1
  let day = time.getDate() > 10 ? time.getDate() : '0' + time.getDate
  let lastday = new Date(year, month, 0).getDate(); //最后一天
  month = month < 10 ? '0' + month : month
  return [year, month, day, lastday].join('-')
}

// 获取本月一日和当前日
function getStartEnd(year, month) {
  year = year || new Date().getFullYear()
  month = month || new Date().getMonth() + 1
  month = month < 10 ? '0' + month : month

  let firstdate = year + '-' + month + '-01';
  let day = new Date(year, month, 0).getDate();
  //let today = new Date().getDate();
  day = day < 10 ? '0' + day : day
  let nowDay = new Date().getDate()
  nowDay = nowDay < 10 ? '0' + nowDay : nowDay

  let nowDate = year + '-' + month + '-' + nowDay
  let lastdate = year + '-' + month + '-' + day; //获取当月最后一天日期
  let nextDate = moment().add(1, 'days').format("YYYY-MM-DD")
  //给文本控件赋值。同下
  return {
    start: firstdate,
    end: lastdate,
    now: nowDate,
    next: nextDate
  };
}

function getTime() {
  let time = new Date()
  let hours = time.getHours()
  hours = hours < 10 ? '0' + hours : hours
  let minute = time.getMinutes()
  minute = minute < 10 ? '0' + minute : minute
  let second = time.getSeconds()
  second = second < 10 ? '0' + second : second
  return [hours, minute, second].join(':')
}

function fetchOption(url, params) {
  let _params = urlencode(params)
  return encodeURI(`${url}?${_params}`)
}

function urlencode(data) {
  let _result = [];
  for (let key in data) {
    let value = data[key] || '';
    if (value.constructor == Array) {
      value.forEach(function (_value) {
        _result.push(key + "=" + _value);
      });
    } else {
      _result.push(key + '=' + value);
    }
  }
  return _result.join('&');
}

function location(address) {
  new QQMapWX({
    key: config.qqAK
  }).geocoder({
    address: address || '',
    success: (res) => {
      let address = res.result.location
      wx.openLocation({
        latitude: address.lat,
        longitude: address.lng,
        scale: 28
      })
    },
    fail: (res) => {
      console.log(res)
    },
    complete: (res) => {
      console.log(res)
    }
  });
}

// 解析经纬度地址
function reverseGeocoord(params, callback) {
  new QQMapWX({
    key: config.qqAK
  }).reverseGeocoder({
    location: params,
    success: (res) => {
      if (res.status == 0) {
        callback(res.result.address)
      }
    },
    fail: (res) => {
      console.log(res)
    },
    complete: (res) => {
      console.log(res)
    }
  });
}

function queryUrl(url) {
  var search = url.substr(url.indexOf('?')); //获取url中"?"符后的字串  
  var theRequest = new Object();
  if (search.indexOf("?") != -1) {
    var str = search.substr(1);
    var strs = str.split("&");
    for (var i = 0; i < strs.length; i++) {
      theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
    }
  }
  return theRequest;
}

function checkContainerNo(ContainerNo) {

  const unicodetbs = [
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "",
    "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "",
    "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "",
    "v", "w", "x", "y", "z"
  ]

  // 转换成小写
  ContainerNo = ContainerNo.toLowerCase().replace(/\s/g, "")

  // 如果位数少于 1位
  if (ContainerNo.length != 11) {
    return false;
  }


  let b = 0
  let c = 0

  for (var i = 0; i < 10; i++) {
    let s = ContainerNo.charAt(i)
    b = unicodetbs.indexOf(s)
    c += Math.round(Math.pow(2, i)) * b
  }

  if ((c % 11) % 10 != ContainerNo.charAt(10)) {
    return false;
  } else {
    return true;
  }
}

function speak(text) {
  // 如果之前的aduio 没播放完全.则立即销毁
  if (innerAudioContext) {
    innerAudioContext.destroy();
    innerAudioContext = null
  }
  wx.request({
    url: `https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=${config.baidu_appid}&client_secret=${config.baidu_apikey}`,
    method: 'GET',
    data: null,
    header: {
      "Content-Type": "application/json"
    },
    success: res => {
      if (res.data) {
        innerAudioContext = wx.createInnerAudioContext()
        innerAudioContext.autoplay = true
        innerAudioContext.src = `https://tsn.baidu.com/text2audio?lan=zh&tok=${res.data.access_token}&cuid=${new Date().getTime()}&ctp=1&tex=` + encodeURIComponent(text);
        innerAudioContext.onPlay(() => {
          console.log('开始播放')
        })
        innerAudioContext.onEnded((res) => {
          console.log('播放结束')
          innerAudioContext.destroy();
          innerAudioContext = null;
        })
      }
    }
  });

}

function unspeak() {
  // 如果之前的aduio 没播放完全.则立即销毁
  if (innerAudioContext) {
    innerAudioContext.destroy();
    innerAudioContext = null
  }
}


// 两地距离. 
// 目的地到当前位置的地理距离
function distance(address) {
  // 
  let end = new Promise((resolve, reject) => {
    new QQMapWX({
      key: config.qqAK
    }).geocoder({
      address: address,
      success: (res) => {
        if (res.status == 0) {
          let location = res.result.location
          resolve({
            latitude: location.lat,
            longitude: location.lng,
          })
        }
      },
      fail: (res) => {
        //console.log(res)
      },
      complete: (res) => {
        //console.log(res)
      }
    });
  })
  

  let start = new Promise((resolve, reject) => {
    wx.getLocation({
      success(res) {
        resolve({
          latitude: res.latitude,
          longitude: res.longitude
        })
      }
    })
  })

  Promise.all([start, end]).then(arr => {
    new QQMapWX({
      key: config.qqAK
    }).calculateDistance({
      mode: 'driving',
      from: arr[0],
      to: [arr[1]],
      success: function (res) {
        console.log(res.result.elements[0].distance)
        /*wx.showToast({
          title: res.result.elements[0].distance + "",
          icon: 'none'
        })*/
      },
      fail: function (res) {
        //console.log(res);
      },
      complete: function (res) {
        //console.log(res);
      }
    });
  })
  
}

export default {
  getYearAndMonth,
  formatTime,
  getDate,
  getTime,
  fetchOption,
  getStartEnd,
  location,
  queryUrl,
  checkContainerNo,
  speak,
  unspeak,
  reverseGeocoord,
  distance
}